import os, sys, string


class UserAccount:
    conn = None
    tlen = None
    retry = 0
    sockretry = 0
    socketpool = None
    client = None
    
    def __init__(self,global_config):
        self.socketpool = global_config['socketclient']
        self.global_config = global_config
    
    def getAccountBySock(self,fromid,toid,status = None):
        result = ''     
        param = {}   
        self.client = self.socketpool.get()
        msg = 'startacc:%s@%s'%(fromid,toid)
        if status:
            msg = '%s@%s'%(msg,status)
        msg = '%s\n'%msg
        import time

        try:
            result = self.client.send(msg)
            self.global_config['sip_logger'].write(result)
            if result.find('@') < 1:
                time.sleep(2) 
                self.client.connect()
                result = self.client.send(msg)

            properlist = result.replace('\n','').split('@')
            for proper in properlist:
                t = proper.split('=')
                param[t[0]]=t[1]
            self.socketpool.put(self.client)
               
        except Exception,error:
            self.global_config['sip_logger'].write(error)
            self.sockretry = self.sockretry + 1;
            if self.sockretry <=3:
                time.sleep(2)
                param = self.getAccountBySock(fromid,toid)
        return param
    
                
    def log_queue(self,attr):

        self.client = self.socketpool.get()

        import datetime
        datetime.datetime.now()

#        v_from = ''
        v_to = ''
#        v_starttime = None
        v_timelong = 0
#        v_ground = None
#        v_realm = None
#        v_prefix = ''
#        v_srvid = '0'
#        v_rate = '0'
#        v_userip = None
#        v_payside = '0'
#        v_linkid = ''
        actstr = []

        for k,v in attr:
            if k not in ('h323-disconnect-time','h323-connect-time','h323-setup-time','call-id','Acct-Session-Id'):
                actstr.append('%s=%s'%(k,v))
#            if k == 'Calling-Station-Id':
#                v_from = v
            if k == 'Called-Station-Id':
                v_to = v
#            if k == 'h323-connect-time':
#                v_starttime = v
            if k == 'Acct-Session-Time':
                v_timelong = v
#            if k == 'Acct-Server-Ground':
#                v_ground = v
#            if k == 'Call-Realm':
#                v_realm = v
#            if k == 'Called-Prefix':
#                v_prefix = v
#            if k == 'Calling-Srvid':
#                v_srvid = v
#            if k == 'Calling-Rate':
#                v_rate = v
#            if k == 'User-Name':
#                v_userip = v
#            if k == 'Calling-Payside':
#                v_payside = v
#            if k == 'Calling-Linkid':
#                v_linkid = v

        if v_to.startswith('TBSV9'):
            return '200'
        endtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        starttime = (datetime.datetime.now()-datetime.timedelta(seconds=v_timelong)).strftime('%Y-%m-%d %H:%M:%S')
        actstr.append('h323-connect-time=%s'%starttime)
        actstr.append('h323-disconnect-time=%s'%endtime)
#        msg = 'Calling-Station-Id=%s@Called-Station-Id=%s@h323-connect-time=%s@h323-disconnect-time=%s@Acct-Session-Time=%d@Acct-Server-Ground=%s@Call-Realm=%s@Called-Prefix=%s@Calling-Srvid=%s@Calling-Rate=%s@User-IP=%s@Calling-Payside=%s@Calling-Linkid=%s\n'% (v_from,v_to,
#            starttime,endtime,v_timelong,v_ground,v_realm,v_prefix,v_srvid,v_rate,v_userip,v_payside,v_linkid)
        msg = '@'.join(actstr)
        result = ''
        import time
        try:
            result = self.client.send('%s\n'%msg)
            if result[0:3] !='200':
                time.sleep(2)
                self.client.connect()
                result = self.client.send(msg)
            self.socketpool.put(self.client)


        except:
            print 'quene connect error'
            self.sockretry = self.sockretry + 1;
            if self.sockretry <=3:
                time.sleep(2)
                result = self.log_queue(attr)

        print result,'------queue--------'

        return result